﻿using DataShower.Interfaces;
using DataShower.ViewModels;
using LiveCharts.Wpf;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;

namespace DataShower.Views;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, IWindowManager
{
    public MainWindow()
    {
        LoginWindow login = new LoginWindow();
        if (!(login.ShowDialog() ?? false))
        {
            App.Current.Shutdown();
            return;
        }
        InitializeComponent();
    }

    public void CloseDialog(bool result)
    {
        if (result)
        {
            this.Close();
        }
    }

    private void ListView_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue is false) return;
        if (sender is not ListView) return;

        ListView view = sender as ListView;

        DataViewModel viewModel = view.DataContext as DataViewModel;
        if (viewModel == null) return;

        int dataCount = viewModel.YCount;
        if (view.View is GridView gv)
        {
            // Y 值加上 序号、总计
            if (gv.Columns.Count == dataCount + 3) return;
        }

        GridView columns = new GridView();
        columns.Columns.Add(new GridViewColumn() { Width = 80, Header = "序号", DisplayMemberBinding = new Binding("Index") });
        columns.Columns.Add(new GridViewColumn() { Width = 80, Header = "X", DisplayMemberBinding = new Binding("X") });
        for (int i = 0; i < dataCount; i++)
        {
            var binding = new Binding($"Y[{i}]");
            columns.Columns.Add(new GridViewColumn()
            {
                Width = 100,
                Header = viewModel.YNames[i],
                DisplayMemberBinding = binding
            });
        }
        columns.Columns.Add(new GridViewColumn() { Width = 100, Header = "总计", DisplayMemberBinding = new Binding("Total") });

        view.View = columns;
    }

    private void CartesianChart_MouseLeave(object sender, MouseEventArgs e)
    {
        CartesianChart chart = sender as CartesianChart;
        foreach (var item in chart.AxisX)
        {
            item.MaxValue = double.NaN;
            item.MinValue = double.NaN;
        }
    }
}